<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <base href="/">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <title>确认订单</title>
    <meta name="keywords" content="">
    <meta name="description" content="">
    <link href="as/css/iconfont/iconfont.css" rel="stylesheet"/>
    <link href="as/css/common.css" rel="stylesheet"/>
    <link href="as/css/cart.css" rel="stylesheet"/>
</head>
<body class="graybg-theme">
<!--头部-->
<div class="topper">
    <div class="wrapper">
        <div class="left-bar">
            <div class="back-home divider">
                <em></em><a href="index.html">商城首页</a>
            </div>
            <div class="item"><a href="">商家中心</a></div>
        </div>
        <div class="right-bar">
            <div class="login-user sub-menu">
                <a class="menu-hd" href="">txtangxia<em></em></a>
                <div class="down">
                    <a href="">内容</a>
                    <a href="">内容</a>
                    <a href="">内容</a>
                </div>
            </div>
            <div class="item"><a href="">消息（<span class="txt-theme">0</span>）</a></div>
            <div class="logout divider"><a href="">退出</a></div>
            <span class=""></span>
            <div class="cart"><em></em><a href="">购物车<span class="txt-theme">2</span>件</a></div>
            <div class="order"><em></em><a href="">我的订单</a></div>
            <div class="fav"><em></em><a href="">我的收藏</a></div>
            <div class="help"><em></em><a href="">帮助中心</a></div>
        </div>
    </div>
</div>
<div class="cart-header wrapper">
    <div class="logo">
        <a href="index.html"><img src="img/logo.png" alt="logo" /></a>
    </div>
    <div class="step-box">
        <div class="row">
            <div class="step first active col-3">
                <span class="num">1</span><span class="line"></span><span class="label">我的购物车</span>
            </div>
            <div class="step active col-3">
                <span class="num">2</span><span class="line"></span><span class="label">确认订单信息</span>
            </div>
            <div class="step col-3">
                <span class="num">3</span><span class="line"></span><span class="label">选择支付方式</span>
            </div>
            <div class="step last col-3">
                <span class="num">4</span><span class="line"></span><span class="label">完成付款</span>
            </div>
        </div>
    </div>
</div>
<!--头部-->

<div class="wrapper confirm-wrap">
    <div class="confirm-tit">
        <span class="tit">选择收货地址 :</span>
    </div>
    <div class="confirm-address clearfix" id="addressList">
        <!-- 地址列表将通过 JavaScript 动态生成 -->
    </div>
    <div class="confirm-address-bar" style="display: none;">
        <a href="javascript:;" class="drop" data-action="drop">显示全部地址</a>
    </div>


    <div class="confirm-tit">
        <span class="tit">确认商品信息:</span><div class="right"><a class="back" href="">返回购物车></a></div>
    </div>
    <div class="confirm-goods">
        <div class="confirm-goods-hd clearfix">
            <div class="col col1">商品信息</div>
            <div class="col col2">单价（元）</div>
            <div class="col col3">数量</div>
            <div class="col col4">小计（元）</div>
        </div>
        <div class="confirm-goods-bd" id="goodsList">
            <!-- 商品信息将动态插入到这里 -->
        </div>

    </div>
    <div class="confirm-total">
        <div class="box">
            <div class="item">应付总额：<strong id="totalAmount"> ¥ 0.00</strong></div>
            <!--<a class="ui-btn-theme go-charge" href="pay.html">去结算</a>-->
            <a class="ui-btn-theme go-charge" href="javascript:;" id="goCharge">去结算</a>
        </div>
    </div>
</div>

<!--脚部-->
<div class="fatfooter">

</div>
<!--脚部-->
<div id="addressform" style="display:none" class="layer-address">
    <form action="">
        <div class="control-group">
            <div class="hd">
                收货人姓名：
            </div>
            <div class="bd">
                <input class="ui-txtin ui-txtin-thin" style="width: 200px;" type="text" name="" id="">
            </div>
        </div>
        <div class="control-group">
            <div class="hd">
                联系电话：
            </div>
            <div class="bd">
                <input class="ui-txtin ui-txtin-thin" style="width: 200px;" type="text" name="" id="">
            </div>
            <div class="hd">或固定电话：</div>
            <div class="bd">
                <input class="ui-txtin ui-txtin-thin" style="width: 200px;" type="text" name="" id="">
            </div>
        </div>
        <div class="control-group">
            <div class="hd vat">
                所在地区：
            </div>
            <div class="bd">
                <select class="ui-txtin ui-txtin-thin" style="width: 180px;" name="">
                    <option value="">选择省</option>
                </select>
                <div class="mt10">
                    <input class="ui-txtin ui-txtin-thin" style="width: 560px;" type="text" name="" id="" placeholder="请填写具体地址，不需要重复填写省/市/区">
                </div>
            </div>
        </div>
        <div class="control-group">
            <div class="hd vat">
                邮政编码：
            </div>
            <div class="bd">
                <input class="ui-txtin ui-txtin-thin" style="width: 200px;" type="text" name="" id="">
            </div>
        </div>
        <div class="control-bottom clearfix">
            <a href="" class="fl btn ui-btn-theme">保存</a><a href="" class="fr btn ui-btn cancle">取消</a>
        </div>
    </form>
</div>
</body>
<script src="js/jquery.js"></script>
<link rel="stylesheet" href="js/icheck/style.css"/>
<script src="js/icheck/icheck.min.js"></script>
<script src="js/layer/layer.js"></script>
<script src="js/global.js"></script>
<script>
    $(document).ready(function() {
        // 获取地址数据
        function loadAddresses() {
            $.ajax({
                url: "/address/getaddressbyuserid",
                type: "GET",
                success: function(response) {
                    if (response && response.code === 0 && response.data) {
                        renderAddresses(response.data);
                    } else {
                        $("#addressList").html("<p>暂无地址信息</p>");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("获取地址数据失败:", error);
                }
            });
        }

        // 渲染地址列表
        function renderAddresses(addresses) {
            let html = "";
            addresses.forEach(address => {
                html += `
                <div class="col col-4">
                    <div class="item ${address.isdefault === 1 ? "active" : ""}" data-address-id="${address.id}">
                        <div class="action">
                            <a class="edit" href="javascript:;">修改</a>
                        </div>
                        <div class="info">
                            <div class="ellipsis"><img src="img/ico/user.jpg" alt="" />${address.name} ${address.tel}</div>
                            <div class="ellipsis"><img src="img/ico/dizhi.jpg" alt="" />${address.province} ${address.city} ${address.area} ${address.address}</div>
                        </div>
                    </div>
                </div>
            `;
            });
            $("#addressList").html(html);

            // 为每个地址项添加点击事件
            $(".item").on("click", function() {
                const addressId = $(this).data("address-id");
                setDefaultAddress(addressId);
            });
        }

        // 设置默认地址
        function setDefaultAddress(addressId) {
            $.ajax({
                url: "/address/setdefault",
                type: "POST",
                data: {
                    id: addressId
                },
                success: function(response) {
                    if (response ) {
                        // 重新加载地址列表
                        loadAddresses();
                    } else {
                        alert("设置默认地址失败");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("设置默认地址失败:", error);
                }
            });
        }

        // 解析 URL 中的商品信息
        function loadGoodsFromURL() {
            const urlParams = new URLSearchParams(window.location.search);
            const selectedItems = [];

            let index = 0;
            while (urlParams.has(`id${index}`)) {
                selectedItems.push({
                    id: urlParams.get(`id${index}`),
                    name: decodeURIComponent(urlParams.get(`name${index}`)),
                    price: parseFloat(urlParams.get(`price${index}`)),
                    quantity: parseInt(urlParams.get(`quantity${index}`))
                });
                index++;
            }

            // 渲染商品信息
            renderGoods(selectedItems);
        }

        // 渲染商品信息
        function renderGoods(goods) {
            let html = "";
            let totalAmount = 0;

            goods.forEach(item => {
                const subtotal = item.price * item.quantity;
                totalAmount += subtotal;

                window.goods2=[];
                const productid=item.id;
                const name=item.name;
                const price=item.price;
                const quantity=item.quantity;

                window.goods2.push({
                    productid:productid,
                    name:name,
                    price:price,
                    number:quantity
                })

                html += `
                <div class="goods clearfix">
                    <div class="col col1">
                        <img src="uploads/11.jpg" alt="">
                        <div class="info">
                            <div class="name">${item.name}</div>
                            <div class="meta"><span>黑色</span><span>S</span></div>
                        </div>
                    </div>
                    <div class="col col2">￥${item.price.toFixed(2)}</div>
                    <div class="col col3">${item.quantity}</div>
                    <div class="col col4">￥${subtotal.toFixed(2)}</div>
                </div>
            `;
            });

            $("#goodsList").html(html);
            $("#totalAmount").text(`￥${totalAmount.toFixed(2)}`);
        }

        // 初始化加载地址和商品信息
        loadAddresses();
        loadGoodsFromURL();

        // 发起 AJAX 请求获取当前用户信息
        $.ajax({
            url: "user/current", // 请求路径
            type: "GET",
            success: function(response) {
                if (response) {
                    const userid = response.userid;
                    window.userid = userid; // 将 userid 存储在全局变量中
                } else {
                    console.log("未获取到用户信息");
                }
            },
            error: function(xhr, status, error) {
                console.error("获取用户信息失败:", error);
            }
        });

        // 点击“去结算”按钮时触发
        $("#goCharge").on("click", function() {
            const totalAmount = parseFloat($("#totalAmount").text().replace("￥", ""));
            const code = "ORDER" + Date.now(); // 使用时间戳生成一个简单的订单编号

            // 发送AJAX请求到后端，创建订单
            $.ajax({
                url: "order/add",
                type: "POST",
                data: {
                    userid: userid,
                    money: totalAmount,
                    code: code
                },
                success: function(response) {
                    if (response.code===200) {
                        console.log(response);
                        window.orderId = parseInt(response.data); // 确保orderId是整数
                        console.log("订单创建成功，orderId:", orderId);

                        // 保存订单商品信息
                        saveOrderItems(orderId);

                        // 保存订单地址信息
                        saveOrderAddress(orderId);
                    } else {
                        alert("订单提交失败1，请重试");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("订单提交失败2:", error);
                    alert("订单提交失败3，请重试");
                }
            });
        });

        // 保存订单商品信息
        function saveOrderItems(orderId) {
            const orderInfoPromises = goods2.map(item => {
                return $.ajax({
                    url: 'orderinfo/add',
                    type: 'POST',
                    data: {
                        orderid: orderId,
                        userid: userid,
                        productid: item.productid,
                        name: item.name,
                        price: item.price,
                        number: item.quantity
                    },
                    success: function(response) {
                        if (response) {
                            console.log("商品信息保存成功");
                        } else {
                            console.log("商品信息保存失败");
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error("商品信息保存失败:", error);
                    }
                });
            });

            // 等待所有商品信息保存完成
            Promise.all(orderInfoPromises)
                .then(() => {
                    console.log("所有商品信息保存成功");
                })
                .catch(error => {
                    console.error("部分商品信息保存失败:", error);
                });
        }

        // 保存订单地址信息
        function saveOrderAddress(orderId) {
            $.ajax({
                url: "address/getdeaddressbyuserid",
                type: "GET",
                success: function(response) {
                    if (response.data) {
                        const addresses = response.data;
                        const selectedAddress = addresses.find(address => address.isdefault === 1);

                        if (!selectedAddress) {
                            alert("请设置默认地址或选择一个地址");
                            return;
                        }

                        // 发送AJAX请求到后端，插入订单地址信息
                        $.ajax({
                            url: "orderaddress/add",
                            type: "POST",
                            data: {
                                orderid: orderId, // 传入orderid
                                userid: userid,
                                name: selectedAddress.name,
                                tel: selectedAddress.tel,
                                province: selectedAddress.province,
                                city: selectedAddress.city,
                                area: selectedAddress.area,
                                address: selectedAddress.address
                            },
                            success: function(response) {
                                if (response) {
                                    console.log("订单地址信息保存成功");
                                    // 跳转到支付页面
                                    console.log(response.data);
                                    location.href="shopping/payment?id="+response.data;

                                } else {
                                    console.log("订单地址信息保存失败");
                                }
                            },
                            error: function(xhr, status, error) {
                                console.error("订单地址信息保存失败:", error);
                            }
                        });
                    } else {
                        alert("获取地址信息失败，请重试");
                    }
                },
                error: function(xhr, status, error) {
                    console.error("获取地址信息失败:", error);
                }
            });
        }
    });
</script>
</html>